import { getUrlSearchByKey } from "../index";
import _ from "lodash";
import { encWbi, getWbiKeys } from "./wbi";
// bvid详情列表
export const BVID_CONCLUSION_KEY = 'bvid';
// bvid=>字幕 映射字典
export const BVID_MAP_SUBTITLE = 'bvid_map_subtitle'

/**
 * 根据 url 获取 视频信息以及字幕，保存在本地。
 * @param url 
 * @returns 
 */
export const onRecieveConclusionUrl = async (url: string) => {
    const result = await chrome.storage.local.get([BVID_CONCLUSION_KEY])
    const _bvidList = result[BVID_CONCLUSION_KEY]
    const [bvid] = getUrlSearchByKey(url, ['bvid'])
    if (!bvid) return _bvidList;
    const info = await fetchVbidInfo(bvid)
    info.conclusionUrl = url
    const bvidList: any[] = _.filter(_bvidList, (data: any) => data.bvid !== bvid)
    bvidList.unshift(info)
    chrome.storage.local.set({ [BVID_CONCLUSION_KEY]: bvidList })
    return bvidList
}

/**
 * 获取视频信息
 * @param bvid
 * @returns
 */
export const fetchVbidInfo = async (bvid: string) => {
    const info = await fetch(`https://api.bilibili.com/x/web-interface/view?bvid=${bvid}`, {
        method: "GET",
    }
    ).then((res) => res.json());
    return info.data
}

export const insertVideoByBvid = async (bvid: string) => {
    const result = await chrome.storage.local.get([BVID_CONCLUSION_KEY])
    const _bvidList = result[BVID_CONCLUSION_KEY]
    const info = await fetchVbidInfo(bvid)
    const bvidList: any[] = _.filter(_bvidList, (data: any) => data.bvid !== bvid)
    bvidList.unshift(info)
    chrome.storage.local.set({ [BVID_CONCLUSION_KEY]: bvidList })
    return bvidList
}


export const getBvidSubtitle = async (bvid: string, cid?: string) => {

    const result = await chrome.storage.local.get([BVID_MAP_SUBTITLE])
    const map = result[BVID_MAP_SUBTITLE] ?? {}
    const { cid: _cid, aid } = await fetchVbidInfo(bvid)
    const ccid = cid || _cid
    const key = _.compact([bvid, ccid]).join("-");
    if (map[key]) {
        return map[key]
    }
    const text = await fetchConclusion(`aid=${aid}&cid=${ccid}`)
    map[key] = text;
    chrome.storage.local.set({ [BVID_MAP_SUBTITLE]: map })
    return text

}

export const fetchConclusion = async (query: string) => {
    const res = await fetch(`https://api.bilibili.com/x/player/wbi/v2?${query}`, {
        method: "GET",
    }
    ).then((res) => res.json());
    // 获取带 auth_key的字幕链接  
    const subtitles = _.find(res?.data?.subtitle?.subtitles, (item: any) => item?.lan === 'ai-zh')
    let subtitle_url = subtitles?.subtitle_url
    if (!subtitle_url) return ''
    if (subtitle_url.startsWith('//')) {
        subtitle_url = 'https:' + subtitle_url
    }
    const subRes = await fetch(subtitle_url, {
        method: "GET",
    }
    ).then((res) => res.json());


    return processSubtitle(subRes?.body || [])
}

/**
 * 获取视频字幕 (废弃)
 * @param bvid
 * @returns
 */
export const getBvidSubtitleDeprecated = async (bvid: string) => {
    const result = await chrome.storage.local.get([BVID_MAP_SUBTITLE])
    const map = result[BVID_MAP_SUBTITLE] ?? {}
    if (map[bvid]) {
        return map[bvid]
    } else {
        const web_keys = await getWbiKeys()
        const
            img_key = web_keys.img_key,
            sub_key = web_keys.sub_key
        const { cid, bvid: _bvid, owner } = await fetchVbidInfo(bvid)
        const up_mid = owner.mid
        const params = { bvid: _bvid, cid, up_mid }
        const query = encWbi(params, img_key, sub_key)
        const text = await fetchConclusion(query)
        map[bvid] = text;
        chrome.storage.local.set({ [BVID_MAP_SUBTITLE]: map })
        return text
    }
}

/**
 * 获取bvid的字幕 (废弃)
 */
export const fetchConclusionDeprecated = async (query: string) => {
    const res = await fetch(`https://api.bilibili.com/x/web-interface/view/conclusion/get?${query}`, {
        method: "GET",
    }
    ).then((res) => res.json());
    return processSubtitle(res?.data?.model_result?.subtitle || [])
}

/**
 * 处理字幕
 */
export const processSubtitle = (subtitles: []) => {
    let content = ''
    subtitles.forEach((sub: any) => {
        content += sub?.content || '';
        content += " "
    })
    return content
}



export const extractBvid = (inputStr: string) => {
    /**
     * 从输入字符串中提取bvid（B站视频标识符）
     * 
     * @param {string} inputStr - 可以是包含bvid的URL，也可以是直接的bvid字符串
     * @returns {string|null} 提取到的bvid字符串，如果未找到则返回null
     */
    // 正则表达式模式：匹配以BV开头，后面跟10个字母或数字的字符串
    const pattern = /BV[a-zA-Z0-9]{10}/;

    // 在输入字符串中搜索匹配的模式
    const match = inputStr.match(pattern);

    // 如果找到匹配项，返回匹配结果，否则返回null
    return match ? match[0] : null;
}


